import {Component, OnInit} from '@angular/core';
import {HttpService} from '../../service/http.service';
import {ActivatedRoute, Params} from '@angular/router';
import 'rxjs/add/operator/switchMap';
import {Book} from '../../module/book';
import {Comment} from '../../module/comment';
import {Cookie} from 'ng2-cookies/ng2-cookies';
import {Email} from '../../module/email';


@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {

  selItem = 0;
  book: Book;
  commentList: Comment[];
  commentCount = 0;
  money = 0;
  push = 0;
  hide = 0;
  commentText: string;
  emailList: Email[];
  emailValue: string;

  constructor(private route: ActivatedRoute,
              private httpService: HttpService) {
  }

  ngOnInit() {
    this.route.params
      .switchMap((params: Params) => this.httpService.getBook(+params['id']))
      .subscribe(r => {
        this.book = r;
        const array = this.book.keywords.split(';');
        this.book.keywordArray = [];
        for (let j = 0; j < array.length; j++) {
          if (array[j] !== '') {
            this.book.keywordArray.push(array[j]);
          }
        }
        this.httpService.getCommentList(r.id, 0).then(s => {
          this.commentList = s;
          this.commentCount = s.length;
        });
      });
  }

  onitemClick(index) {
    this.selItem = index;
  }

  onMoneyClick(index) {
    this.money = index;
  }

  onPushClick(index) {
    if (index === 1) {
      if (Cookie.get('token') != null) {
        this.httpService.getEmails(Cookie.get('token')).then(e => {
          this.emailList = e;
          console.log(this.emailList);
        });
      } else {
        alert('请先登录!');
      }
    }
    this.push = index;
  }

  onclicks(index) {
    this.hide = index;
  }

  /**
   * 提交评论
   */
  submitComment() {
    if (this.commentText == null) {
      alert('评论不能为空!');
      return;
    }
    const token = Cookie.get('token');
    if (token != null) {
      this.httpService.postComment(token, this.book.id, this.commentText).then(s => {
        alert(s);
        location.reload();
      });
    } else {
      alert('请先登录!');
    }
  }

  /**
   * 推送图书
   */
  pushBook() {
    const token = Cookie.get('token');
    if (token != null) {
      this.httpService.pushBook(this.book.id, token, this.emailValue).then(s => {
        alert(s);
        this.onPushClick(0);
      });
    } else {
      alert('请先登录!');
    }
  }


  /**
   * 图书下载
   */
  DownBook() {
    const token = Cookie.get('token');
    if (token != null) {
      alert('下载成功!');
    } else {
      alert('请先登录!');
    }
  }

}
